package main

import (
	"fmt"
	"strings"
)

// 最长公共前缀
// 水平扫描法
func longestCommonPrefix(strs []string) string {
	if len(strs) == 0 {
		return ""
	}
	prefix := strs[0]
	for i := 1; i < len(strs); i++ {
		for len(prefix) > 0 && !strings.HasPrefix(strs[i], prefix) {
			prefix = prefix[:len(prefix)-1]
		}

		if prefix == "" {
			return ""
		}
	}

	return prefix
}

func main() {
	// 测试用例
	testCases := [][]string{
		{"flower", "flow", "flight"},                   // "fl"
		{"interspecies", "interstellar", "interstate"}, // "inter"
	}
	for i, strs := range testCases {
		result := longestCommonPrefix(strs)
		fmt.Printf("测试%d: %v\n", i+1, strs)
		fmt.Printf("结果: \"%s\"\n\n", result)
	}
}
